<?php

class Rss2Parser implements IRssParser
{

    public function __construct(DOMDocument $rssXmlObject)
    {
        $this->xPathHelper = new XPathHelper($rssXmlObject);
    }

    public function GetMainNode()
    {
        return $this->xPathHelper->GetNode("channel");
    }

    public function GetItemNodes()
    {
        return $this->xPathHelper->GetNodes("channel/item");
    }

    public function GetTitle($node)
    {
        return $this->GetText("title", $node);
    }

    public function GetDescription($node)
    {
        $descriptionContent = $this->GetText("description", $node);
        $postContentParser = new PostContentParser($descriptionContent);
        return $postContentParser->GetPureContent();
    }

    public function GetDate($node)
    {
        $addition = ($node->lookupNamespaceURI("dc")) ? " | dc:date" : "";
        $query = "lastBuildDate | pubDate" . $addition;
        return $this->GetText($query, $node);
    }

    public function GetLink($node)
    {
        return $this->GetText("link", $node);
    }

    public function GetAuthor($node)
    {
        $addition = ($node->lookupNamespaceURI("dc")) ? " | dc:creator" : "";
        $query = "author | managingEditor | webMaster" . $addition;
        return $this->GetText($query, $node);
    }

    public function GetPostContent($node)
    {
        $htmlContent = $this->GetPostHtmlContent($node);
        $postContentParser = new PostContentParser($htmlContent);
        return $postContentParser->GetPureContent();
    }

    public function GetPostImage($node, $sourceUrl)
    {
        $htmlContent = $this->GetPostHtmlContent($node);
        $htmlContent = (empty($htmlContent)) ? $this->GetText("description", $node) : $htmlContent;
        $postContentParser = new PostContentParser($htmlContent);
        return $postContentParser->GetPostImage($sourceUrl);
    }

    public function GetCategories($node)
    {
        $categories = array();
        $categoryNodes = $this->xPathHelper->GetNodes("category", $node);
        foreach ( $categoryNodes as $categoryNode )
        {
            $categoryTitle = $this->GetText(".", $categoryNode);
            $rssCategory = new RssCategory();
            $rssCategory->SetTitle($categoryTitle);
            array_push($categories, $rssCategory);
        }
        return $categories;
    }

    private function GetPostHtmlContent($node)
    {
        $rawContent = ( $node->lookupNamespaceURI("content") ) ? $this->GetText("content:encoded", $node) : "";
        return $rawContent;
    }

    /** Wrapper for XPathHelper::GetText method
     *
     */
    private function GetText($expr, $node = null)
    {
        $result = $this->xPathHelper->GetText( $expr, $node );
        return ( $result !== null ) ? $result : "";
    }
}

?>